package com.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * Jwt工具类的封装
 */
public class JwtUtils {
    //设置盐值
    public final static String SING="J*(Y*(&#HBDF~~e";

    /**
     * 生成 JwtToken
     * @param map
     * @return
     */
    public static String getToken(HashMap<String, String> map){

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 7);//七天过期
        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();
        //通过map给payload添加信息
        map.forEach((k,v)->{
            builder.withClaim(k, v);
        });
        String Token = builder.withExpiresAt(instance.getTime())//token过期时间
                .sign(Algorithm.HMAC256(SING));//添加盐值
        return Token;
    }

    /**
     * 验证token信息
     * @param token
     * @return
     */
    public static DecodedJWT verify(String token){
        return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }
}
